package com.comleader.operator.common.util;

import static com.comleader.operator.common.constant.Constant.BATCH_SIZE;
import static com.comleader.operator.common.constant.Constant.SHEET_SIZE;

import java.util.Collection;
import java.util.List;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.PageUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @Dscription EasyExcel工具类
 * @Author 连新景
 * @Date 2024/08/22 17:48
 */
@Slf4j
public class ExcelUtil {

    /**
     * @Description 简单的写，适合数据量不大情况下(1w以内)
     * @Auhtor 连新景
     * @Date 2024/08/22 17:51
     * @param pathName
     * @param head
     * @param sheetName
     * @param data
     */
    public static void writeSimple(String pathName, Class head, String sheetName, Collection<?> data) {
        EasyExcel.write(pathName, head).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet(sheetName).doWrite(data);
    }

    /**
     * @Description 往一个sheet中重复写，适合大数据量情况
     * @Auhtor 连新景
     * @Date 2024/08/22 18:15
     * @param pathName
     * @param head
     * @param sheetName
     * @param data
     */
    public static void writeOneSheetRepeat(String pathName, Class head, String sheetName, List<?> data) {
        try (ExcelWriter excelWriter = EasyExcel.write(pathName, head).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();
            ListUtil.page(data, BATCH_SIZE, list -> {
                log.info("数据量：{}", list.size());
                excelWriter.write(list, writeSheet);
            });
        }
    }

    /**
     * @Description 写到不同的sheet中，适合大数据量情况
     * @Auhtor 连新景
     * @Date 2024/08/22 18:02
     * @param pathName
     * @param head
     * @param sheetName
     * @param sheetSize 每个sheet存放的数据量
     * @param data
     */
    public static void writeMultipleSheet(String pathName, Class head, String sheetName, int sheetSize, List<?> data) {
        int totalSheet = PageUtil.totalPage(data.size(), sheetSize);
        try (ExcelWriter excelWriter = EasyExcel.write(pathName, head).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build()) {
            for (int i = 0; i < totalSheet; i++) {
                WriteSheet writeSheet = EasyExcel.writerSheet(i, sheetName + (i + 1)).build();
                excelWriter.write(ListUtil.page(i, sheetSize, data), writeSheet);
            }
        }
    }

    public static void writeMultipleSheet(String pathName, Class head, String sheetName, List<?> data) {
        writeMultipleSheet(pathName, head, sheetName, SHEET_SIZE, data);
    }

}